package com.dhq.myapp.util

import android.content.Context
import android.os.Environment
import android.util.Log
import com.rokid.cxr.Caps
import com.rokid.cxr.client.extend.CxrApi
import com.rokid.cxr.client.extend.callbacks.GlassInfoResultCallback
import com.rokid.cxr.client.extend.callbacks.PhotoPathCallback
import com.rokid.cxr.client.extend.callbacks.SyncStatusCallback
import com.rokid.cxr.client.extend.infos.GlassInfo
import com.rokid.cxr.client.extend.listeners.BatteryLevelUpdateListener
import com.rokid.cxr.client.extend.listeners.BrightnessUpdateListener
import com.rokid.cxr.client.extend.listeners.MediaFilesUpdateListener
import com.rokid.cxr.client.extend.listeners.VolumeUpdateListener
import com.rokid.cxr.client.utils.ValueUtil
import java.io.File

/**
 * DESC
 * Created by DHQ on 2025/10/11.
 */
class GlassUtil(var mContext: Context) {

    /**
     * 获取设备信息
     */
    fun getGlassesInfo() {
        CxrApi.getInstance().getGlassInfo(object : GlassInfoResultCallback {
            /**
             * Get Glasses information
             *
             * @param status information Got Status
             * @see ValueUtil.CxrStatus
             * @see ValueUtil.CxrStatus.RESPONSE_SUCCEED response succeed
             * @see ValueUtil.CxrStatus.RESPONSE_INVALID response invalid
             * @see ValueUtil.CxrStatus.RESPONSE_TIMEOUT response timeout
             * @param glassesInfo glasses information
             * @see GlassInfo
             */
            override fun onGlassInfoResult(
                status: ValueUtil.CxrStatus?,
                glassesInfo: GlassInfo?
            ) {
                if (status==ValueUtil.CxrStatus.RESPONSE_SUCCEED){
                    //获取设备信息失败

                }else{
                    //获取设备信息失败

                }

            }

        })
    }

    /**
     * Sync Time
     * @return CxrStatus: REQUEST_FAILED, REQUEST_SUCCEED, REQUEST_WAITING
     * REQUEST_SUCCEED: Set time success
     * REQUEST_WAITING: Waiting for response from glasses, Do Not Need Call Again
     * REQUEST_FAILED: Set time failed
     * @see CxrStatus
     */
    fun setTime(): ValueUtil.CxrStatus {
        return CxrApi.getInstance().setGlassTime()
    }



    // Get glasses brightness
    private val glassesBrightnessUpdateListener = object : BrightnessUpdateListener {
        /**
         * Brightness updated
         *
         * @param brightness brightness value range[0-15]
         */
        override fun onBrightnessUpdated(brightness: Int) {

        }
    }
    /**
     * Get glasses brightness
     */
    fun getGlassesBrightness(set : Boolean) {

        CxrApi.getInstance().setBrightnessUpdateListener(if (set) glassesBrightnessUpdateListener else null)
    }

    /**
     * 设置设备亮度
     * Set glasses brightness
     *
     * @param brightness brightness value range[0-15]
     * @return set brightness status
     * @see ValueUtil.CxrStatus
     * @see ValueUtil.CxrStatus.REQUEST_SUCCEED request succeed
     * @see ValueUtil.CxrStatus.REQUEST_WAITING request waiting, do not request again
     * @see ValueUtil.CxrStatus.REQUEST_FAILED request failed
     */
    fun setBrightness(brightness: Int): ValueUtil.CxrStatus? {
        return CxrApi.getInstance().setGlassBrightness( brightness)
    }

    // Get glasses volume
    private val volumeUpdate = object : VolumeUpdateListener {
        /**
         * Volume updated
         *
         * @param volume volume value range[0-15]
         */
        override fun onVolumeUpdated(volume: Int) {

        }

    }

    /**
     * Get glasses volume
     *
     * @param set true:set volume listener false:remove volume listener
     */
    fun getGlassesVolume(set: Boolean){
        CxrApi.getInstance().setVolumeUpdateListener(if (set) volumeUpdate else null)
    }

    /**
     * 设置设备音量
     * Set glasses volume
     *
     * @param volume volume value range[0-15]
     * @return set volume status
     * @see ValueUtil.CxrStatus
     * @see ValueUtil.CxrStatus.REQUEST_SUCCEED request succeed
     * @see ValueUtil.CxrStatus.REQUEST_WAITING request waiting, do not request again
     * @see ValueUtil.CxrStatus.REQUEST_FAILED request failed
     */
    fun setVolume(volume: Int): ValueUtil.CxrStatus? {
        return CxrApi.getInstance().setGlassVolume(volume)
    }


    /**
     * 监听眼镜电量变化
     */
    fun setBatteryListener(listener: BatteryLevelUpdateListener){
//        CxrApi.getInstance().setBatteryLevelUpdateListener(object : BatteryLevelUpdateListener {
//            /**
//             * Battery level updated
//             *
//             * @param level battery level[0-100]
//             * @param charging battery charging status true:charging false:not charging
//             */
//            override fun onBatteryLevelUpdated(level: Int, charging: Boolean) {
//
//            }
//
//        })

        CxrApi.getInstance().setBatteryLevelUpdateListener(listener)
    }



    /**
     * Set glasses sound effect
     *
     * @param value sound effect value "AdiMode0": Loud, "AdiMode1": Rhythm, "AdiMode2": Podcast
     * @return set sound effect status
     * @see ValueUtil.CxrStatus
     * @see ValueUtil.CxrStatus.REQUEST_SUCCEED request succeed
     * @see ValueUtil.CxrStatus.REQUEST_WAITING request waiting, do not request again
     * @see ValueUtil.CxrStatus.REQUEST_FAILED request failed
     */
    fun setSoundEffect(value: String): ValueUtil.CxrStatus?{
        return CxrApi.getInstance().setSoundEffect(value)
    }


    /**
     * 设置关屏时间
     * Set glasses screen off timeout
     *
     * @param seconds timeout value
     *
     * @return set screen off timeout status
     * @see ValueUtil.CxrStatus
     * @see ValueUtil.CxrStatus.REQUEST_SUCCEED request succeed
     * @see ValueUtil.CxrStatus.REQUEST_WAITING request waiting, do not request again
     * @see ValueUtil.CxrStatus.REQUEST_FAILED request failed
     */
    fun setScreenOffTimeout(seconds: Long): ValueUtil.CxrStatus?{
        return CxrApi.getInstance().setScreenOffTimeout(seconds)
    }
    /**
     * 设置power提醒
     * Set glasses power off timeout
     *
     * @param minutes timeout value
     *
     * @return set power off timeout status
     * @see ValueUtil.CxrStatus
     * @see ValueUtil.CxrStatus.REQUEST_SUCCEED request succeed
     * @see ValueUtil.CxrStatus.REQUEST_WAITING request waiting, do not request again
     * @see ValueUtil.CxrStatus.REQUEST_FAILED request failed
     */
    fun setPowerOffTimeout(minutes: Int): ValueUtil.CxrStatus?{
        return CxrApi.getInstance().setPowerOffTimeout(minutes)
    }

    /**
     * 重置
     * Reboot glasses
     *
     * @return reboot glasses status
     * @see ValueUtil.CxrStatus
     * @see ValueUtil.CxrStatus.REQUEST_SUCCEED request succeed
     * @see ValueUtil.CxrStatus.REQUEST_WAITING request waiting, do not request again
     * @see ValueUtil.CxrStatus.REQUEST_FAILED request failed
     */
    fun rebootGlasses(): ValueUtil.CxrStatus{
        return CxrApi.getInstance().notifyGlassReboot()
    }

    /**
     * 关机
     * Shutdown glasses
     *
     * @return shutdown glasses status
     * @see ValueUtil.CxrStatus
     * @see ValueUtil.CxrStatus.REQUEST_SUCCEED request succeed
     * @see ValueUtil.CxrStatus.REQUEST_WAITING request waiting, do not request again
     * @see ValueUtil.CxrStatus.REQUEST_FAILED request failed
     */
    fun shutdownGlasses(): ValueUtil.CxrStatus{
        return CxrApi.getInstance().notifyGlassShutdown()
    }


    // set media files update listener
//    private val mediaFileUpdateListener = object : MediaFilesUpdateListener {
//        /**
//         * media files updated
//         */
//        override fun onMediaFilesUpdated() {
//        }
//    }

    /**
     * 添加眼镜媒体数据监听
     *
     * @param listener
     */
    fun setMediaFilesUpdateListener(listener: FileChangeListener){
//        CxrApi.getInstance().setMediaFilesUpdateListener(listener)
        CxrApi.getInstance().setMediaFilesUpdateListener(object : MediaFilesUpdateListener{
            override fun onMediaFilesUpdated() {
                listener.onFileChanged()
                Log.e("文件变化","---------------")
            }
        })
        CxrApi.getInstance().setBatteryLevelUpdateListener(object : BatteryLevelUpdateListener{
            override fun onBatteryLevelUpdated(p0: Int, p1: Boolean) {
                Log.e("电量变化","--"+p0+"--"+p1)
            }
        })
    }

    /**
     * 发送数据
     */
    private fun sendStatusToMobile() {
        val status = mapOf(
            "battery" to 85,
            "brightness" to 50,
            "volume" to 30,
            "timestamp" to System.currentTimeMillis()
        )

        val caps = Caps().apply {
            write("STATUS_UPDATE")
            write(DataUtils.mapToJson(status))
        }

        CxrApi.getInstance().sendCustomCmd("glass_status", caps)
    }


    //发送自定义数据展示返回结果数据
    fun openCustomView(content: String): ValueUtil.CxrStatus {
        return CxrApi.getInstance().openCustomView(content)
    }


    /**
     * 拍照单张图片
     *
     */
    /** 拍照图片的尺寸  可调整 为了速度目前选择一个小的尺寸
     * [4032x3024, 4000x3000, 4032x2268, 3264x2448, 3200x2400,
     * 2268x3024, 2876x2156, 2688x2016, 2582x1936, 2400x1800,
     * 1800x2400, 2560x1440, 2400x1350, 2048x1536, 2016x1512,
     * 1920x1080, 1600x1200, 1440x1080, 1280x720, 720x1280,
     * 1024x768, 800x600, 648x648, 854x480, 800x480, 640x480,
     * 480x640, 352x288, 320x240, 320x180, 176x144]
     */
    fun takePhoto(listener:SyncListener): ValueUtil.CxrStatus? {
        listener.onTakePhotoStart()
        return CxrApi.getInstance().takeGlassPhoto(320, 240, 100, object :PhotoPathCallback{
            override fun onPhotoPath(
                status: ValueUtil.CxrStatus?,
                path: String?
            ) {
                if (status == ValueUtil.CxrStatus.RESPONSE_SUCCEED){

                    listener.onTakePhotoSuccess(path!!)
                    getFile(path!!,listener)

                }else{
                    listener.onTakePhotoFailed()
                }
            }
        })
    }

    /**
     * 拍照单张图片
     */
    fun takePhoto(photoResult:PhotoPathCallback): ValueUtil.CxrStatus? {
        return CxrApi.getInstance().takeGlassPhoto(320, 240, 100, photoResult)
    }


    /**
     * 根据文件路径获取眼镜文件
     */
    fun getFile(path: String,listener:SyncListener){
        // sync status callback
        val syncCallback = object : SyncStatusCallback {
            /**
             * sync start
             */
            override fun onSyncStart() {
                listener.onSyncStart()
            }

            /**
             * sync single file
             * @param fileName file name which sync success
             */
            override fun onSingleFileSynced(fileName: String?) {
                listener.onSingleFileSynced(fileName!!)
            }

            /**
             * sync failed
             */
            override fun onSyncFailed() {

                listener.onSyncFailed()
            }

            /**
             * sync finished
             */
            override fun onSyncFinished() {

                listener.onSyncFinished()
            }

        }

        val ficturesDir: File? = mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES)

        if (ficturesDir==null){
            listener.onSyncFailed()
        }

        val result = CxrApi.getInstance().syncSingleFile(ficturesDir?.absolutePath,
            ValueUtil.CxrMediaType.PICTURE,path, syncCallback)

        LogUtil.e("同步结果",result.toString())

    }

    //同步所有图片文件
    fun getAllImageFile(){
        val ficturesDir: File? = mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        var types :Array<ValueUtil.CxrMediaType> = arrayOf(ValueUtil.CxrMediaType.PICTURE)
        val syncCallback = object : SyncStatusCallback {
            /**
             * sync start
             */
            override fun onSyncStart() {
            }

            /**
             * sync single file
             * @param fileName file name which sync success
             */
            override fun onSingleFileSynced(fileName: String?) {
                Log.e("同步图片",fileName!!)
            }

            /**
             * sync failed
             */
            override fun onSyncFailed() {
            }

            /**
             * sync finished
             */
            override fun onSyncFinished() {
            }
        }
        CxrApi.getInstance().startSync(ficturesDir?.absolutePath,types, syncCallback)
    }



    interface SyncListener{
        fun onTakePhotoStart()
        fun onTakePhotoSuccess(filePath: String)
        fun onTakePhotoFailed()
        fun onSyncStart()
        fun onSingleFileSynced(fileName: String)
        fun onSyncFailed()
        fun onSyncFinished()
    }


    interface FileChangeListener{
        fun onFileChanged()
    }

}